import { get, set, remove } from '@/utils/auth';
import { ADMIN_KEY } from '@/utils/keys';
import { login, getInfo, logout } from '@/api';

const state = {
  token: get(ADMIN_KEY),
  id: '',
  name: '',
  avatar: '',
  roles: [],
  permissions: [],
};
const mutations = {
  SET_TOKEN (state, token) {
    state.token = token;
    set(ADMIN_KEY, state.token);
  },
  SET_ID (state, id) {
    state.id = id;
    set('ACCOUNT_ID', state.id);
  },
  SET_NAME (state, name) {
    state.name = name;
    set('ACCOUNT', state.name);
  },
  SET_AVATAR (state, avatar) {
    state.avatar = avatar;
    set('AVATAR', state.avatar);
  },
  SET_ROLES (state, roles) {
    state.roles = roles;
    set('ROLES', state.roles);
  },
  SET_PERMISSIONS (state, permissions) {
    state.permissions = permissions;
  },
};
const actions = {
  // 登录
  async login ({ commit }, userInfo) {
    const data = {
      code: userInfo.code,
      password: userInfo.password,
      username: userInfo.username,
      uuid: userInfo.uuid,
    };
    await login(data).then(res => {
      if (200 == res.code) {
        set(ADMIN_KEY, res.data.access_token);
        commit('SET_TOKEN', res.data.access_token);
        return 'success';
      } else {
        return Promise.reject(new Error('faile'));
      }
    });
  },
  // 获取用户信息
  async getInfo ({ commit, state }) {
    await getInfo()
      .then(res => {
        const user = res.user;
        const { userId, nickName, avatar } = user;
        if (res.roles.length > 0) {
          commit('SET_ROLES', res.roles);
          commit('SET_PERMISSIONS', res.permissions);
        } else {
          commit('SET_ROLES', ['ROLE_DEFAULT']);
        }
        commit('SET_ID', userId);
        commit('SET_NAME', nickName);
        commit('SET_AVATAR', avatar);
      })
      .catch(error => {
        commit('SET_TOKEN', '');
        return Promise.reject(error);
      });
  },
  // 退出登录
  async logOut ({ commit, state }) {
    logout(state.token)
      .then(res => {
        commit('SET_TOKEN', '');
        commit('SET_ROLES', []);
        commit('SET_PERMISSIONS', []);
        remove(ADMIN_KEY);
        location.href = '/web'
        return Promise.resolve(res);
      })
      .catch(error => {
        return Promise.reject(error)
      });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
